import axios, {
  type AxiosError,
  type AxiosRequestConfig,
  type AxiosRequestHeaders,
  type InternalAxiosRequestConfig,
} from "axios";

import { getCookie } from "@/utils/cookie";

const DURATION = 10000;
const pendingRequests = new Map();

export const service = axios.create({
  timeout: DURATION,
});

const getRequestKey = (config: InternalAxiosRequestConfig<any>) => {
  return `${config.url}/${JSON.stringify(config.params)}/${JSON.stringify(
    config.data,
  )}&request_type=${config.method}`;
};

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    // 拦截重复的请求
    const requestKey = getRequestKey(config);
    if (pendingRequests.has(requestKey)) {
      config.cancelToken = new axios.CancelToken((cancel) => {
        cancel(`重复的请求被主动拦截: ${requestKey}`);
      });
    } else {
      pendingRequests.set(requestKey, config);
    }

    // 配置
    config.headers = {
      "Content-Type": "application/json",
      "app-version": getCookie("app-version") || "50",
      "device-type": getCookie("device-type") || "android",
      languageId: getCookie("languageId") || "in",
      accessToken: getCookie("webToken") || getCookie("accessToken"),
      semiAccessToken: getCookie("semiAccessToken"),
      adjustId: getCookie("google_ad_id") || getCookie("adjust_id"),
      ...config.headers,
    } as never;

    return config;
  },
  (err: AxiosError) => Promise.reject(err),
);

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    const requestKey = getRequestKey(response.config);
    if (requestKey) {
      pendingRequests.delete(requestKey);
    }
    return Promise.resolve(response);
  },
  (error) => {
    if (axios.isCancel(error)) {
      return Promise.reject(error);
    }
    pendingRequests.clear();
    return Promise.reject(error);
  },
);

export interface ResponseData<T> {
  errCode: string;
  success: boolean;
  errMsg: string;
  data: T;
}

export async function request<T>(options: AxiosRequestConfig) {
  return await service.request<ResponseData<T>>(options).then((res) => res.data);
}

export async function get<T>(url: string, params = {}) {
  return request<T>({ method: "GET", url, params });
}

export async function post<T>(url: string, data = {}, params = {}, headers?: AxiosRequestHeaders) {
  return request<T>({ method: "POST", url, data, params, headers });
}

export async function put<T>(url: string, data = {}, headers = {}) {
  return request<T>({ method: "PUT", url, data, headers });
}
